package com.ebt.m.activity;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;
import com.ebt.m.AppContext;
import com.ebt.m.R;
import com.ebt.m.commons.buscomponent.thirtylogin.model.ShareListener;
import com.ebt.m.commons.utils.Logger;
import com.ebt.m.customer.constant.CustomerConstant;
import com.ebt.m.customer.event.EventActivityResultForAttachment;
import com.ebt.m.customer.event.EventMultiChooseOff;
import com.ebt.m.customer.event.SharedElementEvent;
import com.ebt.m.customer.ui.FragmentCustomerMain;
import com.ebt.m.customer.util.CustomerNavigator;
import com.ebt.m.customer.util.MultiChooseManager;
import com.ebt.m.data.bean.UserInfo;
import com.ebt.m.event.SwitchBottomTabEvent;
import com.ebt.m.fragment.AppsFragment;
import com.ebt.m.fragment.MineFragment;
import com.ebt.m.homepage.DynamicFragment;
import com.ebt.m.proposal_v2.utils.ProposalUtils;
import com.ebt.m.share.ShareUtils;
import com.ebt.m.update.UpdateService;
import com.ebt.m.utils.TalkingDataUtil;
import com.ebt.m.view.BottomBar;
import com.ebt.m.view.PlusUnionView;
import com.ebt.m.view.SpaceItem;
import com.ebt.m.widget.BaseActivity;
import com.tencent.tauth.Tencent;
import org.greenrobot.eventbus.EventBus;


/**
 * 主界面
 *
 * @author dell
 */
public class MainActivity extends BaseActivity implements BottomBar.OnItemClickClickListener, PlusUnionView.OnPlusClickLitener {

    private Fragment mContentCurr;
    private Fragment mContentPrev;
    private String[] mTitles;
    private BottomBar mBottomBar;
    private PlusUnionView mPlusUnion;

    public static final String INTENT_ACTION_FROM = "intent_action_from";
    public static final String INTENT_ACTION_FROM_REFRESH = "intent_action_from_refresh";

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        try {
            if (intent.getStringExtra(INTENT_ACTION_FROM).equals(INTENT_ACTION_FROM_REFRESH)) {
                SwitchBottomTabEvent bottomTabEvent = new SwitchBottomTabEvent();
                bottomTabEvent.pos = 0;
                EventBus.getDefault().post(bottomTabEvent);
            }
        } catch (Exception e) {
            Logger.e(e);
        }
    }

    @Override
    public void onClick(View v) {
        mPlusUnion.setVisibility(View.GONE);
        UserInfo userLicenceInfo = AppContext.getCurrentUser();
        switch (v.getId()) {
            case R.id.action_proposal:
                ProposalUtils.makeDefaultProposal(mContext);
                TalkingDataUtil.onEventWithAgentId(TalkingDataUtil.TYPE_BOTTOM_PLUS_PROPOSAL_V270);
                break;
            case R.id.action_customer:
                CustomerNavigator.startActivityCustomerDetail(getContext());
                TalkingDataUtil.onEventWithAgentId(TalkingDataUtil.TYPE_BOTTOM_PLUS_CUSTOMER_V270);
                break;
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTitles = getResources().getStringArray(R.array.main_bottom_items);
        new UpdateService(this).updateVersion(null);
        initShareListeners();
    }

    @Override
    protected void init() {
        super.init();
        initView();
        initDatas();
    }

    public void initView() {
        mBottomBar = (BottomBar) findViewById(R.id.main_bottom_tablayout);
        mPlusUnion = (PlusUnionView) findViewById(R.id.plus_union);
        mPlusUnion.setOnPlusClickListener(this);
        mBottomBar.addSpaceItem(new SpaceItem(mTitles[0], R.drawable.bottom4home, R.drawable.bottom4home_selected));
        mBottomBar.addSpaceItem(new SpaceItem(mTitles[1], R.drawable.bottom4customer, R.drawable.bottom4customer_selected));
        mBottomBar.addSpaceItem(new SpaceItem(mTitles[2], R.drawable.bottom4applications, R.drawable.bottom4applications_selected));
        mBottomBar.addSpaceItem(new SpaceItem(mTitles[3], R.drawable.bottom4mine, R.drawable.bottom4mine_selected));
        mBottomBar.setOnItemClickClickListener(this);
    }

    public void initDatas() {
        switchContent(0);
    }

    public void switchContent(int pos) {
        mContentPrev = mContentCurr;
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        String tag = getTagByPos(pos);
        mContentCurr = fragmentManager.findFragmentByTag(tag);
        if (mContentCurr == null) {
            switch (pos) {
                case 0:
                    mContentCurr = new DynamicFragment();
                    break;
                case 1:
                    mContentCurr = FragmentCustomerMain.newInstance();
                    break;
                case 2:
                    mContentCurr = AppsFragment.newInstance();
                    break;
                case 3:
                    mContentCurr = new MineFragment();
                    break;
            }
        }
        TalkingDataUtil.onEventWithAgentId(getTKEventByPos(pos));
        if (mContentPrev != null) {
            transaction.hide(mContentPrev);
        }
        if (!mContentCurr.isAdded()) {
            transaction.add(R.id.content_frame, mContentCurr, tag).commitAllowingStateLoss();
        } else {
            transaction.show(mContentCurr).commitAllowingStateLoss();
        }
    }

    private String getTagByPos(int pos) {
        String tag = "";
        switch (pos) {
            case 0:
                tag = "dynamic";
                break;
            case 1:
                tag = "customer";
                break;
            case 2:
                tag = "appcations";
                break;
            case 3:
                tag = "mine";
                break;

        }
        return tag;
    }

    private String getTKEventByPos(int pos) {
        String event = "";
        switch (pos) {
            case 0:
                event = TalkingDataUtil.TYPE_BOTTOM_ICON_FIRST_PAGE_V270;
                break;
            case 1:
                event = TalkingDataUtil.TYPE_BOTTOM_ICON_CUSTOMER_V270;
                break;
            case 2:
                event = TalkingDataUtil.TYPE_BOTTOM_ICON_APP_V270;
                break;
            case 3:
                event = TalkingDataUtil.TYPE_BOTTOM_ICON_MINE_V270;
                break;
        }
        return event;
    }

    private long firstTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (mContentCurr != null && mContentCurr instanceof FragmentCustomerMain) {
                    if (MultiChooseManager.getInstance().getInMultiChooseMode()) {
                        MultiChooseManager.getInstance().setInMultiChooseMode(false);
                        EventBus.getDefault().post(new EventMultiChooseOff());
                        return true;
                    }
                }
                long secondTime = System.currentTimeMillis();
                if (secondTime - firstTime > 2000) {
                    Toast.makeText(this, "再按一次退出" + getResources().getString(R.string.app_name), Toast.LENGTH_SHORT).show();
                    firstTime = secondTime;
                    return true;
                } else {
                    finish();
                }
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) {
            EventBus.getDefault().post(new EventActivityResultForAttachment(requestCode, resultCode, data));
            return;
        }
        if (FragmentCustomerMain.REQUEST_CODES != null
                && FragmentCustomerMain.REQUEST_CODES.contains(requestCode)) {
            EventBus.getDefault().post(new EventActivityResultForAttachment(requestCode, resultCode, data));
            return;
        }
        Tencent.onActivityResultData(requestCode, resultCode, data, mShareListener);
    }

    public ShareListener getShareListener() {
        return mShareListener;
    }

    private ShareListener mShareListener;

    private void initShareListeners() {
        mShareListener = new ShareListener() {
            @Override
            public void onShareError(String platform, String errorInfo) {
                if (!TextUtils.isEmpty(errorInfo)) {
                    Toast.makeText(getContext(), errorInfo, Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getContext(), ShareUtils.getZhFromEn(platform, getContext())
                            + getContext().getString(R.string.share_failed), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onShareComplete(String platform) {
                Toast.makeText(getContext(), ShareUtils.getZhFromEn(platform, getContext())
                        + getContext().getString(R.string.share_completed), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onShareCancel(String platform) {
                Toast.makeText(getContext(), ShareUtils.getZhFromEn(platform, getContext()) + getContext().getString(R.string.share_canceled), Toast.LENGTH_SHORT).show();
            }
        };
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //super.onSaveInstanceState(outState);
    }

    @TargetApi(22)
    @Override
    public void onActivityReenter(int resultCode, Intent data) {
        super.onActivityReenter(resultCode, data);
        if (data != null
                && CustomerConstant.SharedElement.FROM_CUSTOMER_ALL
                .equals(data.getStringExtra(CustomerConstant.SharedElement.FROM))) {
            EventBus.getDefault().post(new SharedElementEvent(data));
        }
    }

    @Override
    public void spaceItemClick(int oldIndex, int newIndex, SpaceItem spaceitem) {
        switchContent(newIndex);
    }

    @Override
    public void centerButtonClick(View view) {
        if (mPlusUnion.getVisibility() == View.GONE) {
            mPlusUnion.setVisibility(View.VISIBLE);
            mPlusUnion.onResume();
        }
    }
}